package com.siyoumi.sh.modules.jm;

import cn.hutool.json.JSONObject;
import com.siyoumi.sh.component.ThreadContext;
import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.jm.entity.*;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//积分夺宝
@Slf4j
public class FunWinHandle
        extends JmHandleBase
        implements IHandle {
    //fun_win wan 商品ID序号

    @Override
    @SneakyThrows
    public void run() {
        List<String> args = ThreadContext.getArgs();
        if (args.size() < 3) {
            log.error("args参数异常，参考：fun_win wan 投注数量 商品ID序号，{}", args);
            return;
        }
        String server = args.get(1);
        JmApiData apiData = getApiDataByServer(server);
        if (apiData == null) {
            log.error("args server参数异常，{}", args);
            return;
        }
        setJmApiData(apiData);

        List<JmApiToken> apiTokenArr = getJmApiData().getJmApiTokens();
        if (apiTokenArr.size() <= 0) {
            log.error("未配置TOKEN");
            return;
        }
        JmApiToken apiToken = apiTokenArr.get(0);


        List<FunWinPrize> listPrize = funPrizeList(apiToken);
        List<FunWinPrize> listPrizeTrue = new ArrayList<>();

        DateTimeFormatter mmdd = DateTimeFormatter.ofPattern("MM-dd HH:mm");

        Integer index = 0;
        for (FunWinPrize goods : listPrize) {
            Integer rDate = goods.getState();
            if (goods.getState() == 1) {
                continue;
            }
            log.info("[{}]{}: {} - {}", index, goods.getPsend_name()
                    , XDate.format(goods.getFunwin_start_date(), mmdd)
                    , XDate.format(goods.getFunwin_end_date(), mmdd));
            index++;

            listPrizeTrue.add(goods);
        }

        Integer goodsIndex;
        if (args.size() >= 4) {
            goodsIndex = XStr.toInt(args.get(3));
        } else {
            String s = "";
            while (true) {
                log.info("请输入需要抢的商品序号：");
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                s = br.readLine();
                if (XStr.hasAnyText(s)) {
                    break;
                }
            }
            goodsIndex = XStr.toInt(s, 0);
        }

        if (goodsIndex > (listPrizeTrue.size() - 1)) {
            log.info("你请输入商品序号异常");
            return;
        }

        Integer touCount = XStr.toInt(args.get(2), 1);
        FunWinPrize goods = listPrizeTrue.get(goodsIndex);
        qiang(apiTokenArr, goods, touCount);
    }

    /**
     * 开始投标
     */
    public void qiang(List<JmApiToken> apiTokenArr, FunWinPrize prize, Integer touCount) {
        log.info("{}-积分夺宝", prize.getPsend_name());

        for (JmApiToken jmApiToken : apiTokenArr) {
            log.info("{}-{}开始投{}注", prize.getPsend_name(), jmApiToken.getName(), touCount);
            XReturn r = funTou(jmApiToken, prize, touCount);
            log.info("{}-{}", prize.getPsend_name(), r.getErrMsg());
        }
    }

    //夺宝列表
    public List<FunWinPrize> funPrizeList(JmApiToken apiToken) {
        String apiUrl = XStr.concat(getApiRoot(), "__api_java__/z_app/fun_win/web/get_prize_list?"
                , "page=1&page_size=30&site_id=", getSiteId()
                , "&", apiToken.getWxFromQuery()
        );

        XReturn r = forApi(apiUrl);
        List<FunWinPrize> listPrize = new ArrayList<>();
        if (r.ok()) {
            List<Map> listData = (List<Map>) r.getData("list_data");
            for (Map item : listData) {
                FunWinPrize prize = new FunWinPrize();

                prize.setFunwin_id((String) item.get("funwin_id"));
                prize.setPsend_name((String) item.get("psend_name"));
                prize.setFunwin_start_date(XDate.parse((String) item.get("funwin_start_date")));
                prize.setFunwin_end_date(XDate.parse((String) item.get("funwin_end_date")));
                prize.setFunwin_total((Integer) item.get("funwin_total"));
                prize.setState((Integer) item.get("__button_state"));
                listPrize.add(prize);
            }
        }

        return listPrize;
    }

    //投注
    public XReturn funTou(JmApiToken apiToken, FunWinPrize entityPrize, Integer touCount) {
        String apiUrl = XStr.concat(getApiRoot(), "__api_java__/z_app/fun_win/web/launch?"
                , "site_id=", getSiteId()
                , "&prize_id=", entityPrize.getFunwin_id()
                , "&total=" + touCount
                , "&", apiToken.getWxFromQuery()
        );

        XReturn r = forApi(apiUrl);
        return r;
    }

}
